import { constantRouterMap, asyncRouterMap } from '@/router'
import store from '../index'
/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param asyncRouterMap
 * @param routesMap
 */
function filterAsyncRouter(constantRouterMap, routesMap) {
  let accessedRouters = constantRouterMap.filter(route => {
    if (route.hidden){ //去除login 和404
      return true;
    }
    if (route.children){
      route.children=filterAsyncRouter(route.children,routesMap);
    }
    return route.meta.permissionCode.includes(routesMap)
  })
  // //再次遍历，因为每个路由只有一个children，所有这边是伪递归
  // accessedRouters=accessedRouters.filter(route=>{
  //
  // })
  return accessedRouters
}

const SET_ROUTERS = 'SET_ROUTERS'

const permission = {
  state: {
    addRouters: '',
    routers: constantRouterMap
  },
  mutations: {
    [SET_ROUTERS](state, routers) {
      state.addRouters = routers
      state.routers = routers
    }
  },
  actions: {
    /*
    过滤用户权限菜单列表
     */
    filterAuthRouters({commit},{permissionCode}){
      return new Promise((resolve, reject) => {
        let accessRouters=filterAsyncRouter(constantRouterMap,permissionCode);
        commit(SET_ROUTERS,accessRouters);
        resolve()
      });
    }
  },
  getters: {
    addRouters: state => state.addRouters,
    routers: state => state.routers
  }
}

export default permission
